package jdk12;

import org.junit.Test;

public class SwitchExpressions {

	/*
	 * 传统的switch声明语句(switch statement)在使用中有一些问题：
	 * 	匹配是自上而下的，如果忘记写break, 后面的case语句不论匹配与否都会执行；
	 * 	所有的case语句共用一个块范围，在不同的case语句定义的变量名不能重复；
	 * 	不能在一个case里写多个执行结果一致的条件；
	 * 	整个switch不能作为表达式返回值；
	*/
	// 传统写法
	@Test
	public void old() {
		int numberOfLetters;
		Fruit fruit = Fruit.APPLE;
		switch (fruit) {
		case PEAR:
			numberOfLetters = 4;
			break;
		// case 穿透
		case APPLE:
		case GRAPE:
		case MANGO:
			numberOfLetters = 5;
			break;
		case ORANGE:
		case PAPAYA:
			numberOfLetters = 6;
			break;
		default:
			throw new IllegalStateException("No Such Fruit:" + fruit);
		}
		System.out.println(numberOfLetters);

	}

	// java 12的新特性
	@Test
	public void newFeature() {
		Fruit fruit = Fruit.APPLE;
		switch (fruit) {
		case PEAR -> System.out.println("4");
		case APPLE, GRAPE, MANGO -> System.out.println("5");
		case ORANGE, PAPAYA -> System.out.println("6");
		default -> throw new IllegalStateException("No Such Fruit:" + fruit);
		}

		int numberOfLetters; 
		// 可以作为一个表达式返回结果
		numberOfLetters = switch (fruit) {
		case PEAR -> 4;
		case APPLE, GRAPE, MANGO -> 5;
		case ORANGE, PAPAYA -> 6;
		default -> throw new IllegalStateException("No Such Fruit:" + fruit);
		};
		System.out.println(numberOfLetters);
	}

}

enum Fruit {
	PEAR, APPLE, GRAPE, MANGO, ORANGE, PAPAYA;
}
